package com.example.libraryapp.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.libraryapp.R;
import com.example.libraryapp.util.Validator;

/**
 * 用戶注册
 */
public class RegisterActivity extends Activity {

	private EditText etUsername;
	private EditText etNickname;
	private EditText etPassword;
	private Button bnRegister; // 注册按钮

	private Activity mActivity;
	private static Context mContext;
	private static final String TITLE = "注册";
	private UserInfo userInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		init();
		findViews();
		setListeners();
	}

	/**
	 * 初始化
	 */
	private void init() {
		mActivity = RegisterActivity.this;
		mContext = RegisterActivity.this;
		userInfo = new UserInfo();
	}

	/**
	 * 找到控件
	 */
	private void findViews() {
		// 标题栏
		// 登录
		etUsername = (EditText) findViewById(R.id.et_username);
		etNickname = (EditText) findViewById(R.id.et_nickname);
		etPassword = (EditText) findViewById(R.id.et_password);
		bnRegister = (Button) findViewById(R.id.bn_register);
	}

	private void setListeners() {
		// 注册
		bnRegister.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				String cardId = etUsername.getText().toString().trim();
				
				if (!Validator.isEffective(cardId)) {
					Toast.makeText(mContext, "用户名不能为空！", 1).show();
					return;
				}
				userInfo.setCardid(cardId);
				
				String username = etNickname.getText().toString().trim();
				if (!Validator.isEffective(username)) {
					Toast.makeText(mContext, "昵称不能为空！", 1).show();
					return;
				}
				userInfo.setUsername(username);
				
				
				String password = etPassword.getText().toString().trim();
				if (!Validator.isEffective(password)) {
					Toast.makeText(mContext, "密码不能为空！", 1).show();
					return;
				}
				userInfo.setPassword(password);
				// 用户注册
				userRegister(userInfo);
			}
		});
	}

	/**
	 * 用户注册
	 */
	private void userRegister(UserInfo userInfo) {
		boolean registerResult = UserService.register(mContext, userInfo);
		if (registerResult) {
			Toast.makeText(mContext, "注册成功！", 1).show();
			registerSuccess();
		} else {
			Toast.makeText(mContext, "注册失败！", 1).show();
		}
	}

	/**
	 * 注册成功以后的处理
	 */
	private void registerSuccess() {
		// 把注册的用户名和密码传递到登录页面
		Intent intent = new Intent();
		intent.putExtra("user", userInfo);
		mActivity.setResult(1, intent);
		mActivity.finish();
	}
}
